//
//  LoginViewController.m
//  JiuLe
//
//  Created by xcq on 15/11/1.
//  Copyright © 2015年 Fine. All rights reserved.
//

#import "Common.h"
#import "RESideMenu.h"
#import "JlUserManager.h"
#import <GTSDK/GeTuiSdk.h>
#import <IQKeyboardManager.h>
#import "MallViewController.h"
#import "LoginViewController.h"
#import "CYLTabBarController.h"
#import "MyZoneViewController.h"
#import "ServiceViewController.h"
#import "MessageViewController.h"
#import "ActivateViewController.h"
#import "HomePageViewController.h"
#import "ConnectionDeviceViewController.h"
#import "SideMenuContentViewController.h"
#import <IQKeyboardManager/IQKeyboardManager.h>

@interface LoginViewController() <UITextFieldDelegate> {
    CGRect imgViewRect;
    CGFloat topConstant;
}

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UILabel *userNameTip;
@property (weak, nonatomic) IBOutlet UILabel *passWordTip;
@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UITextField *passWord;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *goActivityBtn;

@end

#define kUserNameTag  0x22
#define kPassWordTag  0x21

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _userName.tag = kUserNameTag;
    _passWord.tag = kPassWordTag;

    NSString *userName = [[NSUserDefaults standardUserDefaults]objectForKey:UserDataName];
    if (userName!=nil&&![userName isEqualToString:@""]) {
        _userName.text = userName;
        
    }
    imgViewRect = _icon.frame;
    _userName.delegate = self;
    _passWord.delegate = self;
    [_scrollView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self
                                                                              action:@selector(touchesView)]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[IQKeyboardManager sharedManager] setEnable:NO];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[IQKeyboardManager sharedManager] setEnable:YES];

}

- (IBAction)goActivityEvent:(UIButton *)sender {
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:JiuLeOfflineMode];
    [self setRootController];
    [GeTuiSdk unbindAlias:[JlUserManager shareInstance].userInfo.userid];
    ConnectionDeviceViewController *activate = [[ConnectionDeviceViewController alloc] initWithNibName:@"ConnectionDeviceViewController" bundle:nil];
    BaseNavController *active = [[BaseNavController alloc] initWithRootViewController:activate];
    [[JlUserManager shareInstance].menu setContentViewController:active];
//    [self.sideMenuViewController setContentViewController:manager.baseTab animated:YES];
    [[JlUserManager shareInstance].menu hideMenuViewController];}

///键盘显示事件
- (void) keyboardWillShow:(NSNotification *)notification {
    //获取键盘高度，在不同设备上，以及中英文下是不同的
    CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
    //计算出键盘顶端到inputTextView panel底端的距离(加上自定义的缓冲距离INTERVAL_KEYBOARD)
    CGFloat offset = CGRectGetMaxY(_loginBtn.frame) - (CGRectGetHeight(self.view.frame) - kbHeight) + 10;
    if (offset > 61) {
        offset = 61;
    }
    
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //将视图上移计算好的偏移
    if(offset > 0) {
        [UIView animateWithDuration:duration animations:^{
            self.scrollView.contentOffset = CGPointMake(0, offset);
        }];
    }
}

///键盘消失事件
- (void) keyboardWillHide:(NSNotification *)notify {
    // 键盘动画时间
    double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //视图下沉恢复原状
    [UIView animateWithDuration:duration animations:^{
        _scrollView.contentOffset = CGPointZero;
    }];
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    if (textField.text.length > 0) {
        if (textField.tag == kPassWordTag) {
            _passWord.returnKeyType = UIReturnKeyJoin;
        }
        return YES;
    }
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.tag == kUserNameTag) {
        if ([textField isFirstResponder]) {
            [_passWord becomeFirstResponder];
        }
    } else if (textField.tag == kPassWordTag) {
        if (textField.text.length > 0) {
            _passWord.returnKeyType = UIReturnKeyJoin;
            [self login:nil];
            return YES;
        }
        if ([textField isFirstResponder]) {
            _passWord.returnKeyType = UIReturnKeyNext;
            [_userName becomeFirstResponder];
        }
    }
    return YES;
}

- (void)touchesView {
    [self.view endEditing:YES];
}

- (IBAction)login:(id)sender {
    //TODO:网络请求
    if (_userName.text.length == 0) {
        TIPSFORVIEW(@"用户名不能为空！");
        return;
    } else if (_passWord.text.length == 0) {
        TIPSFORVIEW(@"密码不能为空！");
        return;
    }
    __weak LoginViewController *weakSelf = self;
    [SVProgressHUD showWithStatus:@"登录中.." maskType:SVProgressHUDMaskTypeClear];
    [InterfaceNetManager RequestLogin:_userName.text PassWord:_passWord.text completion:^(BOOL isSucceed,
                                                                                          NSString *message,
                                                                                          id data,
                                                                                          NSError *error) {
        [SVProgressHUD dismiss];
        if (isSucceed) {
            UserInfoModel *model = [UserInfoModel objectWithKeyValues:data];
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:JiuLeOfflineMode];
            [NSUserDefaults  setUserObject:model forKey:UserInfoUserDefault];
            BOOL bol =  [[[NSUserDefaults standardUserDefaults] objectForKey:@"push"] boolValue];
            if (bol==NO) {
                [GeTuiSdk bindAlias:[JlUserManager shareInstance].userInfo.userid];
            }
            [NSUserDefaults setObject:_passWord.text forKey:UserDataPassWord];
            [NSUserDefaults setObject:_userName.text forKey:UserDataName];
            [SVProgressHUD showSuccessWithStatus:@"登陆成功!"];
            [weakSelf performSelector:@selector(setRootController)
                           withObject:@{@"bol":@(YES)}
                           afterDelay:1.f];
        } else {
            TIPSFORVIEW(message);
        }
    }];
}

- (void)setRootController {
        JlUserManager *manager = [JlUserManager shareInstance];
        CYLTabBarController *tabbar = [[CYLTabBarController alloc] init];
        [self setUpTabBar:tabbar];
        manager.baseTab=tabbar;
        SideMenuContentViewController *personal  = getStoryOfControllerInstance(@"SideMenuContentViewController");
        BaseNavController *base = [[BaseNavController alloc] initWithRootViewController:personal];
        personal.navigationController.navigationBarHidden = YES;
        
        RESideMenu *sideMenu              = [[RESideMenu alloc] init];
        sideMenu.leftMenuViewController   = base;
        sideMenu.contentViewController    = tabbar;
        sideMenu.menuPreferredStatusBarStyle = UIStatusBarStyleLightContent;
        sideMenu.backgroundImage       = [UIImage imageNamed:@"bg"];
        sideMenu.contentViewShadowColor   = [UIColor blackColor];
        sideMenu.contentViewShadowOffset  = CGSizeMake(0, 0);
        sideMenu.contentViewShadowOpacity = 0.6;
        sideMenu.contentViewShadowRadius  = 12;
        sideMenu.contentViewShadowEnabled = YES;
        sideMenu.interactivePopGestureRecognizerEnabled = YES;
        sideMenu.contentViewScaleValue = 0.9;
        sideMenu.panGestureEnabled        = YES;
        sideMenu.panFromEdge              = NO;
        manager.menu = sideMenu;
        self.view.window.rootViewController = manager.menu;
   
}

- (void)setUpTabBar:(CYLTabBarController *)_tabbar {
    
    HomePageViewController *home = getStoryOfControllerInstance(@"HomePageViewController");
    BaseNavController *baseNav1 = [[BaseNavController alloc] initWithRootViewController:home];
    
    MallViewController *mall = getStoryOfControllerInstance(@"MallViewController");
    
    ServiceViewController *service = getStoryOfControllerInstance(@"ServiceViewController");
    BaseNavController *baseNav3 = [[BaseNavController alloc] initWithRootViewController:service];
    
    MessageViewController *message = getStoryOfControllerInstance(@"MessageViewController");
    BaseNavController *baseNav4 = [[BaseNavController alloc] initWithRootViewController:message];
    
    MyZoneViewController *myZone = getStoryOfControllerInstance(@"MyZoneViewController");
    
    [self customizeTabBarForController:_tabbar];
    
    // set the text color for unselected state
    // 普通状态下的文字属性
    NSMutableDictionary *normalAttrs = [NSMutableDictionary dictionary];
    normalAttrs[NSForegroundColorAttributeName] = [UIColor blackColor];
    normalAttrs[NSFontAttributeName] = [UIFont fontWithName:kfontName size:14.];
    
    // set the text color for selected state
    // 选中状态下的文字属性
    NSMutableDictionary *selectedAttrs = [NSMutableDictionary dictionary];
    selectedAttrs[NSForegroundColorAttributeName] = [UIColor colorWithHex:0x217AB9];
    selectedAttrs[NSFontAttributeName] = [UIFont fontWithName:kfontName size:14.];
    // set the text Attributes
    // 设置文字属性
    UITabBarItem *tabBar = [UITabBarItem appearance];
    [tabBar setTitleTextAttributes:normalAttrs forState:UIControlStateNormal];
    [tabBar setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];
    
    [_tabbar setViewControllers:@[
                                            baseNav1,
                                            baseNav4,
                                            baseNav3,
                                            mall,
                                            myZone,
                                            ]];
}

- (void)customizeTabBarForController:(CYLTabBarController *)tabBarController {
    
    
    NSDictionary *dict1 = @{
                            CYLTabBarItemTitle : @"首页",
                            CYLTabBarItemImage : @"nav_home",
                            CYLTabBarItemSelectedImage : @"nav_home_cur",
                            };
    NSDictionary *dict2 = @{
                            CYLTabBarItemTitle : @"商城",
                            CYLTabBarItemImage : @"nav_shop",
                            CYLTabBarItemSelectedImage : @"shop_selete",
                            };
    NSDictionary *dict3 = @{
                            CYLTabBarItemTitle : @"服务",
                            CYLTabBarItemImage : @"nav_service",
                            CYLTabBarItemSelectedImage : @"ser2_ico",
                            };
    NSDictionary *dict4 = @{
                            CYLTabBarItemTitle : @"消息",
                            CYLTabBarItemImage : @"nav_mail",
                            CYLTabBarItemSelectedImage : @"mail2_ico(1)"
                            };
    NSDictionary *dict5 = @{
                            CYLTabBarItemTitle : @"我的",
                            CYLTabBarItemImage : @"nav_me",
                            CYLTabBarItemSelectedImage : @"me2_ico"
                            };
    NSArray *tabBarItemsAttributes = @[
                                       dict1,
                                       dict4,
                                       dict3,
                                       dict2,
                                       dict5
                                       ];
    tabBarController.tabBarItemsAttributes = tabBarItemsAttributes;
    
    UIColor *titleHighlightedColor = [UIColor darkGrayColor];
    [[UITabBarItem appearance] setTitleTextAttributes:
     [NSDictionary dictionaryWithObjectsAndKeys: titleHighlightedColor, NSForegroundColorAttributeName,iOS8Font(16.f), NSFontAttributeName, nil] forState:UIControlStateSelected];
    UIImage *tabbarimage=[UIImage imageNamed:@"nav_bg"];
    UIImageView *tabBarBackgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0,
                                                                                           tabBarController.tabBar.frame.size.width, tabBarController.tabBar.frame.size.height)];
    //tabBarBackgroundImageView.contentMode = UIViewContentModeScaleAspectFit;//效果将按原图原来的比例缩放
    tabBarBackgroundImageView.image =tabbarimage;
    [tabBarController.tabBar insertSubview:tabBarBackgroundImageView atIndex:1];

}


- (void)dealloc {
    removeObserver();
}

@end
